package com.gao.controller;

import com.gao.entity.User;
import com.gao.entity.UserExample;
import com.gao.service.IUserService;
import com.gao.util.ResultVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * @author gao
 * @time 2020/05/28 17:13:49
 */
public
@RestController
class UserController {

    private
    @Autowired
    IUserService userService;

    @PostMapping("user/save")
    public ResultVO save(@RequestBody User user) {
        userService.save(user);
        return ResultVO.success("增加用户成功");
    }

    @PostMapping("user/delete")
    public ResultVO delete(@RequestBody String id) {
        if (id == null) {
            throw new RuntimeException("id为null");
        }
        userService.delete(Integer.valueOf(id));
        return ResultVO.success("删除用户成功");
    }

    @PostMapping("user/update")
    public ResultVO update(@RequestBody User user) {
        userService.update(user);
        return ResultVO.success("修改用户成功");
    }

    @PostMapping("user/findById")
    public ResultVO findById(@RequestBody String id) {
        if (id == null) {
            throw new RuntimeException("id为null");
        }
        User user = userService.findById(Integer.valueOf(id));
        return user != null ? ResultVO.success("查询用户成功", user) : ResultVO.failure("查询用户失败");
    }

    @PostMapping("user/findAll")
    public ResultVO findAll() {
        List<User> list = userService.findAll();
        return ResultVO.success("查询用户成功", list);
    }

    /**
     * @param map 搜索参数
     *            pageNum 起始页，pageSize 每页显示行数
     *            minId id大于minId
     *            maxId id小于maxId
     *            etc.
     * @return
     */
    @PostMapping("user/search")
    public ResultVO search(@RequestBody(required = false) Map map) {
        if (map == null) {
            return ResultVO.success("查询所有用户", userService.findAll());
        }
        UserExample ue = new UserExample();
        String s = (String) map.get("minId");
        String s2 = (String) map.get("maxId");
        if (Objects.nonNull(s)) {
            ue.or().andIdGreaterThanOrEqualTo(Integer.valueOf(s));
        }
        if (Objects.nonNull(s2)) {
            ue.or().andIdLessThanOrEqualTo(Integer.valueOf(s));
        }
        // etc.  TBD

        s = (String) map.get("pageNum");
        s2 = (String) map.get("pageSize");
        int[] pages = null;
        if (Objects.nonNull(s) && Objects.nonNull(s2)) {
            int pageNum = Integer.valueOf(s);
            int pageSize = Integer.valueOf(s2);
            pages = new int[]{pageNum, pageSize};
        }
        List<User> list = userService.search(ue, pages);
        return ResultVO.success("搜索用户成功", list);
    }


}
